package com.ali.juejin.base

import android.content.Intent
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.ali.juejin.bean.CommonReponseBean
import com.ali.juejin.ui.activity.LoginActivity
import com.blankj.utilcode.util.ActivityUtils.startActivity
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import retrofit2.HttpException

open class BaseModelView: ViewModel() {

    val mContext by lazy { BaseApplication.getContext() }
    private val sp by lazy { SPUtils.getInstance() }

    fun<T> request(
        execute:suspend CoroutineScope.() -> Unit,
                onError: (error: Throwable) -> Unit = {}
    ){
        viewModelScope.launch(errorHandler<T> { onError.invoke(it) }) {
            launch(Dispatchers.IO){
                execute()
            }
        }
    }

    private fun<V> errorHandler(onError: (error: Throwable) -> Unit): CoroutineExceptionHandler {
        return CoroutineExceptionHandler { _, throwable ->

            LogUtils.wTag("错误1",throwable.message)
            LogUtils.wTag("错误2",throwable is HttpException)
            if(throwable is HttpException){
                val response = throwable.response()?.errorBody()
                val str = response?.string()
                LogUtils.wTag("网络错误",str)
                val resultType = object : TypeToken<CommonReponseBean<V>>() {}.type
                val gson = Gson()
                val fromJson = gson.fromJson<CommonReponseBean<V>>(str, resultType)
                ToastUtils.showShort("错误信息"+fromJson.m)
            }

            onError.invoke(throwable)
        }
    }

    // 未登录则跳转到登录页
    fun interceptLogin():Boolean{
        val token = sp.getString("token","")
        if(token.isNullOrEmpty()){
            startActivity(Intent(mContext, LoginActivity::class.java))
            return false
        }
        return true
    }

}